<template>
  <div>
    <el-dialog title="添加广告位信息" :visible.sync="dialogAdd.show" width="40%">
      <el-form :model="spot" ref="formAdd" label-width="100px" :rules="rules">
        <el-form-item label="类型" prop="type">
          <el-input v-model="spot.type" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="规格" prop="size">
          <el-input v-model="spot.size" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="图片路径" prop="image">       </el-form-item>
          <el-upload
            style="padding-left: 20%;padding-bottom: 10%"
            class="upload-demo"
            drag
            action="https://sm.ms"
            :http-request="uploadImage"
            >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        <el-form-item label="所在小区" prop="communityName">
          <el-select v-model="spot.communityId" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in spot.community"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('formAdd')">取 消</el-button>
        <el-button type="primary" @click="dialogFormAdd('formAdd')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import spotApi from '@/api/spot/spot'
import communityApi from '@/api/community/community'

export default {
  name: 'addSpot',
  props: {
    dialogAdd: Object
  },
  data () {
    return {
      value: '',
      spot: {
        communityId: '', // 小区编号
        type: '', // 广告位类型
        size: '', // 广告位规格
        image: '', // 广告位图片
        community: [] // 小区列表
      },
      rules: { // 表单验证规则
        type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
        size: [{required: true, message: '规格不能为空', trigger: 'blur'}],
        image: [{required: true, message: '图片路径不能为空', trigger: 'blur'}],
        communityId: [{required: true, message: '所在小区不能为空', trigger: 'blur'}]
      }
    }
  },
  methods: {
    /**
     * 上传图片
     * 调用公共图床api上传图片放回图片的url路径
     * @param req
     * @returns {Promise<void>}
     *
     */
    async uploadImage (req) {
      let _that = this
      const config = {
        headers: {'Content-Type': 'multipart/form-data'}
      }
      // eslint-disable-next-line no-unused-vars
      var fileType = ''
      if (req.file.type === 'image/png') {
        fileType = 'png'
      } else {
        fileType = 'jpg'
      }
      const formData = new FormData()
      formData.append('smfile', req.file)
      this.$axios.post('https://sm.ms/api/upload', formData, config)
        .then(res => {
          _that.spot.image = res.data.url
          _that.$message({
            type: 'success',
            message: '添加成功'
          })
        })
        .catch(err => {
          console.log(err.message)
          _that.$message({
            type: 'warning',
            message: '添加失败'
          })
        })
    },
    /**
     * 添加广告位表单取消按钮点击事件，清除表单内容并隐藏表单
     */
    handleCancel (formAdd) {
      this.$refs[formAdd].resetFields()
      this.spot.communityId = null
      this.dialogAdd.show = false
    },
    /**
     * 通过调用api获取小区列表信息
     */
    getCommunityInfo () {
      communityApi.getAllCommunities().then(res => {
        this.spot.community = res.data
      })
    },
    /**
     * 添加广告位表单提交按钮点击事件，将广告位对象作为参数传给api来实现添加数据，添加成功后清除表单内容
     * 将表单隐藏并更新广告位列表
     */
    dialogFormAdd (formAdd) {
      this.$refs[formAdd].validate((valid) => {
        if (valid) {
          spotApi.addSpot(this.spot).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.$refs[formAdd].resetFields()
            this.spot.communityId = null
            this.dialogAdd.show = false
            this.$emit('update')
          }
          )
        } else {
          return false
        }
      })
    }
  },
  /**
   * 创建页面时，获取小区列表
   */
  created () {
    this.getCommunityInfo()
  }
}
</script>

<style scoped>

</style>
